<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style type="text/css">
        body {
            text-align: center;
            padding-top: 20px;
        }
        canvas {
            box-shadow: 0 0 10px #333;
            margin: 0 auto;
        }
    </style>
</head>
<body onload="draw()">
<canvas id="canvas" width="800" height="600">
    你的浏览器太 low 了，请更新~!
</canvas>

<script>
    function draw() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');

            function Ball(x, y, r, speedX, speedY, color) {
                // 设置属性
                this.x = x;
                this.y = y;
                this.r = r;
                this.speedX = speedX;
                this.speedY = speedY;
                this.color = color;

                // 设置方法
                this.draw = function () {
                    ctx.beginPath();
                    ctx.fillStyle = this.color;
                    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
                    ctx.fill();
                };

                this.move = function () {
                    this.x += this.speedX;
                    if (this.x > canvas.width - this.r || this.x < this.r) {
                        this.speedX *= -1;
                    }

                    this.y += this.speedY;
                    if (this.y > canvas.height - this.r || this.y < this.r) {
                        this.speedY *= -1;
                    }
                }
            }

            var ball = new Ball(100, 100, 50, 2, 2, 'blue');
            ball.draw();

            function start() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ball.draw();
                ball.move();
                window.requestAnimationFrame(start);
            }

            start();
        }
    }
</script>
</body>
</html>
